<script setup lang="ts">
import { addApi, deleteApi, getIdApi, queryAllApi, updateApi } from "@/api/dept";
import { onMounted, ref } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import type { DeptModel, DeptModelArray } from "@/api/model/model";
/*表格组件信息数据*/
//const deptList = ref<DeptModel[]>([]);
const deptList = ref<DeptModelArray[]>([]);
//编辑点击事件
const handleEdit = async (index: number, row: DeptModel) => {
  console.log(index, row);

  //1.获取当前行部门的id
  let id = row.id;
  //2.根据部门id异步请求获取部门数据
  if (id) {
    let result = await getIdApi(id);

    if (result.code) {
      //3.将部门数据绑定给模型数据deptForm
      deptForm.value = result.data;
      //4.设置对话框标题为"修改部门"
      title.value = "修改部门";
      //5.展现对话框
      dialogFormVisible.value = true;
    }
  }

};
//删除点击事件
const handleDelete = (index: number, row: DeptModel | undefined) => {
  console.log(index, row);
  ElMessageBox.confirm(
    '这是一项很危险的操作，确认要删除吗?',
    '删除警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if(!row || !row.id) {
        return;
      }
      let result = await deleteApi(row.id);
      //判断是否删除成功或是失败
      if (result.code) {
        //删除成功发送提示
        ElMessage.success("删除成功");
        //重新查询更新后的列表
        queryAll();
      } else {
        //删除失败发送失败提示
        ElMessage.error("好像失败了呢")
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
};
//查询数据方法
const queryAll = async () => {
  //发送异步请求获取列表数据
  let result = await queryAllApi();
  // let result = await axios.get("http://localhost:8080/depts");
  //更新模型数据部门列表:deptList
  deptList.value = result.data;
};
//勾子函数调用查询数据
onMounted(() => {
  queryAll();
});
/*新增或修改部门对话框数据*/
const dialogFormVisible = ref<boolean>(false);
const deptForm = ref<DeptModel>({
  name: ""
});
const title = ref<string>("");
//新增或修改确定按钮点击事件
const saveOrUpdate = async (formE1: FormInstance | undefined) => {
  if (!formE1) return;
  await formE1.validate(async (valid, fields) => {
    if (valid) {
      //新增或修改操作：deptForm有id属性值就做修改，没有id属性值就做新增
      let result;
      if (deptForm.value.id) {
        //修改
        result = await updateApi(deptForm.value);
      } else {
        //调用新增异步请求
        result = await addApi(deptForm.value);
      }

      //判断返回结果是否成功
      if (result.code) {

        if (deptForm.value.id) {
          //提示“修改成功”
          ElMessage.success("修改成功");
        } else {
          //提示“添加成功”
          ElMessage.success("添加成功");
        }
        //关闭当前对话框
        dialogFormVisible.value = false;
        //重置表单数据
        deptForm.value = { name: "" };
        //重新查询数据
        queryAll();
      } else {
        //添加失败，提示失败消息 result.msg
        ElMessage.error(result.msg);
      }
    } else {
      console.log("error submmit", fields);
    }
  });
};
/*表单校验数据*/
const ruleFormRef = ref<FormInstance>();
const rules = ref<FormRules<DeptModel>>({
  name: [
    { required: true, message: "部门名称不能为空", trigger: "blur" },
    //required: true代表必填
    //message: "部门名称不能为空"校验失败的时候提示的消息
    //trigger: "blur"设置触发检验数据的事件，这里失去焦点检验不能为空
    { min: 2, max: 10, message: "部门名称的长度为2~10个字符", trigger: "blur" },
    //min: 2, max: 10 代表最小长度为2，最大长度为10
    {
      pattern: /[\u4e00-\u9fff0]{2,}\w*/,
      message: "部门名称至少2个中文字符开头",
      trigger: "blur",
    },
  ],
});
</script>

<template>
  <h1>部门管理</h1>
  <br>
  <el-button
    type="primary"
    @click="
    title = '新增部门';
    dialogFormVisible = true;
    "
  >&nbsp;&nbsp;&nbsp;+&nbsp;新增部门&nbsp;&nbsp;&nbsp;&nbsp;
  </el-button>
  <br><br>
  <el-table :data="deptList" border style="width: 100%">
    <el-table-column
      type="index"
      label="序号"
      width="100"
      align="center"
    ></el-table-column>
    <el-table-column prop="name" label="部门名称" width="280" align="center"></el-table-column>
    <el-table-column
      prop="updateTime"
      label="最后操作时间"
      width="280"
      align="center"
    />
    <el-table-column prop="op" label="操作" align="center">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--新增或修改部门对话框-->
  <el-dialog v-model="dialogFormVisible" title="title" width="500">
    <!--
    ref="ruleForm"设置当前表单对象唯一标识符，可以使用这个标识符代表操作哪个表单
    rules="rules"校验表单数据规则对象
    -->
    <el-form :model="deptForm" ref="ruleFormRef" :rules="rules">
      <!--prop="name"设置具体校验的表单元素标签，与rules里面对应的检验字段名一样-->
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="
        dialogFormVisible = false
        deptForm = { name: '' };
        "
        >取消
        </el-button>
        <el-button type="primary" @click="saveOrUpdate(ruleFormRef)">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
